﻿var dataPoint = GetUrlParam("dataPointID");
var dataType = GetUrlParam("dtype");
var detype = decodeURI(GetUrlParam("dtp"));
var device = decodeURI(GetUrlParam("dev"));
var YMax;//曲线图Y轴最大值
var YMin;//曲线图Y轴最小值
var start;//查询的起始时间
var end;//查询的截止时间
//当前页码
var pageindex = 1;
var curpagesize = 10;
var tabType = "chart";//设置tab当前页类型，chart为曲线，table为表格
//初始化页面参数


$(document).ready(function () {
    //浮点或整型
    if (dataType!= 2 && dataType != 3) {
        $(".nav-tabs-custom ul li:eq(1)").hide();
        tabType = "table";
        $("#chart").removeClass("active");
        $("#data").addClass("active");
        
    }

    //初始化当前变量
    var desc = "&nbsp&nbsp资产描述:" + device + "&nbsp&nbsp" + detype + "&nbsp&nbsp";
    $('#device').html(desc);
    //初始化时间控件
    InitdatePicker();
    if (tabType == "chart") {
        CreateLine();
    }
    else {
        InitTable(0,pageindex);
    }
    //点击搜索
    $("#search").click(function () {
        //点击查询时，如果当前页面为曲线图页面，则加载曲线图，并同时更新数据表格
        //如当前页不是曲线图页面，则由tab切换事件来延迟加载曲线图数据
        if (tabType == "chart") {
            CreateLine();
        }
        else {
            InitTable(0,pageindex);
        }
    });

    //tab页切换
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var obj = e.target; // 激活的标签页
        var val = $(this).attr("val");
        tabType = val;
        if (tabType == "chart") {
            CreateLine();
        }
        else if (tabType == "table") {
            pageindex = 1;
            InitTable(0,pageindex);
        }
    });
});
//初始化Table
function InitTable(index,pgindex) {
    var start = $('#daterange-btn span').attr("start");
    var end = $('#daterange-btn span').attr("end");
    var oTableInit = new Object();
    //列表
    var columns = [
        {
            name: "编号", field: "id", formatter: function (val) {
                index = index+1
                return index;
            }},
        { name: "数据", field: "data" },
        {
            name: "更新时间", field: "createTime", formatter: function (val) {
                return formatDate(val);
            }
        },
        { name: "终端编号", field: "terminalID" }
    ];
    //分页
    var param = { filter: dataPoint, pagesize: curpagesize, pageindex: pgindex, startTime: start, endTime: end };
    $("#hisTable").datagrid({ columns: columns, dblclick: void (0) }).loadData(host_name + "record/list", "post", param, function () {
        $.ajax({
            url: host_name + "record/count?filter=" + dataPoint + "&startTime=" + start + "&endTime=" + end,
            type: "get",
            success: function (data) {
                if (data <= curpagesize) {
                    $("#example").hide();
                }
                else {
                    $("#example").show();
                    totalcount = Math.ceil(data / curpagesize)
                    $('#pageLimit').bootstrapPaginator({
                        currentPage: pgindex,
                        totalPages: totalcount,//总页数
                        numberOfPages: pagenum,//显示页数
                        size: "normal",
                        bootstrapMajorVersion: 3,
                        alignment: "right",
                        itemTexts: function (type, page, current) {
                            switch (type) {
                                case "first": return "首页";
                                case "prev": return "上一页";
                                case "next": return "下一页";
                                case "last": return "末页";
                                case "page": return page;
                            }//默认显示的是第一页。
                        },
                        onPageClicked: function (event, originalEvent, type, page) {//给每个页眉绑定一个事件，其实就是ajax请求，其中page变量为当前点击的页上的数字。
                            index = (page - 1) * curpagesize;
                            InitTable(index,page);
                        }
                    });
                }

            }
        });
    });
};
function CreateLine() {
    var start = $('#daterange-btn span').attr("start");
    var end = $('#daterange-btn span').attr("end");
    var myChart = echarts.init(document.getElementById('load_line'));
    var resLine = [];//数据缓存数组，显示曲线需将对象转换成数组
    var res = {};//数据缓存对象
    var plot_line;
    $.ajax({
        type: "get",
        url: host_name + "record/dataList?filter=" + dataPoint + "&startTime=" + start + "&endTime=" + end,
        success: function (doc) {
            var legendData = [];
            var xData = [];
            var yData = [];
            var resLine = [];
            for (var i = 0; i < doc.length; i++) {
                //设置曲线图数据
                var myDate = new Date(doc[i].createTime)
                var year = myDate.getFullYear();
                var month = myDate.getMonth();
                var day = myDate.getDate();
                var hour = myDate.getHours();
                var min = myDate.getMinutes();
                var sec = myDate.getSeconds();
                var d = year + "-" + (month + 1) + "-" + day + " " + hour + ":" + min + ":" + sec;//设置当前数据值对应的时间
                xData.push(d);
                var identity = JSON.parse(doc[i].data);
                yData.push(identity.Value);
                res[device] = {
                    labelVal: dataPoint,
                    name: device,
                    type: 'line',
                    showSymbol: false,
                    lineStyle: {
                        normal: {
                            width: 1
                        }
                    },
                    data: yData,
                    xDataVal: xData
                };
                legendData.push(identity.Value);
                resLine.push(res[device]);
            }
            // 为echarts对象加载数据
            var notMerge = true;//设置是否和刷新前的数据合并                        
            drawLine(myChart, legendData, xData, resLine, notMerge)
        }
    });
    $('#load_line').bind("mouseleave", function () {
        $("#tooltip").remove();
    });
}
//绘制曲线图
function drawLine(chart, legendData, xData, resLine, notMerge) {

    option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            left: "center",
            width: 600,
            data: ['实时数据']
        },
        calculable: true,
        colors: ["#415ead"],
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                splitLine: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: "#666666"//x轴，y轴的数字颜色
                    }
                },
                textStyle: {
                    fontSize: "14px",
                    color: "green",
                    align: "center"
                },
                axisLabel: {
                    formatter: function (value, idx) {
                        var myDate = new Date(value);
                        var year = myDate.getFullYear();
                        var month = myDate.getMonth();
                        var day = myDate.getDate();
                        var hour = myDate.getHours();
                        var min = myDate.getMinutes();
                        var hours = hour < 10 ? "0" + hour : hour;
                        var minutes = min < 10 ? "0" + min : min;
                        return year + "-" + (month + 1) + "-" + day + " " + hours + ":" + minutes;
                    }
                },
                data: xData
            }
        ],
        yAxis: [
            {
                min: YMin,
                max: YMax,
                scale: true,
                type: 'value',
                splitNumber: (YMax - YMin) / 20,
                textStyle: {
                    fontSize: "14px",
                    color: "green"
                },
                boundaryGap: [0, '100%'],
                splitLine: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: "#666666"//x轴，y轴的数字颜色
                    },
                    formatter: '{value}'
                }
            }
        ],
        series: [
            {
                name: '数据值',
                type: 'line',
                data: legendData
            }]
    };
    chart.setOption(option, notMerge);
}
function InitdatePicker() {
    $('#daterange-btn').daterangepicker(
        {
            startDate: moment().subtract('days', 6),
            endDate: moment(),
            ranges: {
                //'最近1小时': [moment().subtract('hours',1), moment()],
                '今日': [moment().startOf('day'), moment()],
                '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
                '最近7日': [moment().subtract('days', 6), moment()],
                '最近30日': [moment().subtract('days', 29), moment()]
            },
            opens: 'right', //日期选择框的弹出位置
            applyClass: 'btn-small btn-primary blue',
            cancelClass: 'btn-small',
            locale: {
                applyLabel: '确定',
                cancelLabel: '取消',
                fromLabel: '起始时间',
                toLabel: '结束时间',
                customRangeLabel: '自定义',
                daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'],
                firstDay: 1
            }
        }, function (start, end, label) {//格式化日期显示框
            $('#daterange-btn span').attr("start", start.format('YYYY-MM-DD'));
            $('#daterange-btn span').attr("end", end.format('YYYY-MM-DD'));
            $('#daterange-btn span').html(start.format('YYYY年MM月DD日') + ' - ' + end.format('YYYY年MM月DD日'));
        });
    $('#daterange-btn span').attr("start", moment().subtract('days', 6).format('YYYY-MM-DD'));
    $('#daterange-btn span').attr("end", moment().format('YYYY-MM-DD'));
    $('#daterange-btn span').html(moment().subtract('days', 6).format('YYYY年MM月DD日') + ' - ' + moment().format('YYYY年MM月DD日'));
}
//格式化数据，如将时间字段格式化为yyyy-MM-dd HH:mm:ss
function formatDataTime(model) {
    if (model == null) return "";
    var t = new Date(model);
    model = t.getFullYear() + "-" + p(t.getMonth() + 1) + "-" + p(t.getDate()) + " " + p(t.getHours()) + ":" + p(t.getMinutes()) + ":" + p(t.getSeconds());
    return model;
}